import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入想查询的路径");
        System.out.print("->");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()){
            System.out.println("输入的文件路径有误！");
            return;
        }
        System.out.println("请输入想查询的 关键字");
        System.out.print("->");
        String key = scanner.next();
        scan(rootFile,key);

    }

    private static void scan(File rootFile, String key) {
        if(!rootFile.isDirectory()){
            return;
        }
        File[] files = rootFile.listFiles();
        if(files == null|| files.length == 0){
            return;
        }
        for (File f : files){
            if(f.isFile()){
                doSearch(f,key);
            }else {
                scan(f,key);
            }
        }
    }

    private static void doSearch(File f, String key) {
        StringBuilder sb = new StringBuilder();
        try(Reader reader = new FileReader(f)){
            char[] chars = new char[1024];
            while(true){
                int n = reader.read(chars);
                if(n == -1){
                    break;
                }
                String s = new String(chars,0,n);
                sb.append(s);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        if(sb.indexOf(key) == -1){
            return;
        }
        System.out.println("找到目标文件" + f.getAbsolutePath());
    }
}
